package com.satyam.smooth.dbunit.demo;

import com.satyam.smooth.util.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import org.dbunit.DatabaseUnitException;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.DatabaseSequenceFilter;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.FilteredDataSet;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.filter.ITableFilter;
import org.dbunit.dataset.xml.FlatXmlDataSet;

/**
 *
 * @author srt
 */
public class DBExporter {

    private static String _testDir = "dbDump";
    private static String _dbFile = "dbDump.xml";
    private static String _driverClass = "com.mysql.jdbc.Driver";
    private static String _jdbcConnection = "jdbc:mysql://localhost/smoothinventory";
    private static String userName = "root";
    private static String password = "";
    private static String _testTableName = "user";
    private static Logger log = LoggerFactory.make();

    public static void main(String[] args) throws ClassNotFoundException, DatabaseUnitException, DataSetException, IOException, SQLException {
        fullDatabaseExport(new File(_testDir, _dbFile));
    }

    public static void fullDatabaseExport(File file) throws ClassNotFoundException,
            DatabaseUnitException,
            DataSetException,
            IOException,
            SQLException {
        IDatabaseConnection connection = getConnection();

        ITableFilter filter = new DatabaseSequenceFilter(connection);
        IDataSet dataset = new FilteredDataSet(filter, connection.createDataSet());
        log.debug("The file is being written");
        FlatXmlDataSet.write(dataset, new FileOutputStream(file));
        log.debug("The file has been written and the file path is " + file.getAbsolutePath());
    }

    public static IDatabaseConnection getConnection() throws ClassNotFoundException,
            DatabaseUnitException,
            SQLException {
        // database connection
        Class driverClass = Class.forName(_driverClass);
        Connection jdbcConnection = DriverManager.getConnection(_jdbcConnection, userName, password);
        return new DatabaseConnection(jdbcConnection);
    }
}
